package com.jilujia.domain.question;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.jilujia.domain.question.repository.AnswerRepository;
import com.jilujia.domain.question.repository.QuestionRepository;
import com.jilujia.framework.domain.AbstractPoEntityManager;

@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class AnswerManager extends AbstractPoEntityManager<Long, Answer, AnswerRepository> {
	
	@Autowired
	private QuestionRepository questionRepository;

	@Transactional
	public Answer saveAnswer(Answer answerVo, Long userId) {
		// 持久化question
		Question question = questionRepository.findOne(answerVo.getQuestion().getId());
		answerVo.setQuestion(question);
		
		// 初始化PO
		Answer answerPo = new Answer();
		
		// new Answer
		Date now = new Date(System.currentTimeMillis());
		answerPo.setCreatedDate(now);
		answerPo.setModifyDate(now);
		answerPo.setUserId(userId);
		
		// 直接发布
		
		// 把VO属性copy到PO上
		answerPo.processVo(answerVo);
		
		// 之前所有的动作都是为了生成完整的PO
		this.setInstance(answerPo);
		this.save();
		
		return answerPo;
	}
	
	@Transactional
	public void addCommentCount() {
		Answer answer = this.getInstance();
		answer.setCommentCount(answer.getCommentCount() + 1);
		this.save();
	}

	@Transactional
	public void changeVoteCount(boolean useful) {
		Answer answer = this.getInstance();
		if (useful) {
			answer.setVoteCount(answer.getVoteCount() + 1);
		} else {
			answer.setVoteCount(answer.getVoteCount() - 1);
		}
		this.save();
	}
	
	
}
